package com.chao.ioc.factory;

import com.chao.ioc.bean.BeanDefinition;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : Rookie
 * @description :
 * @date : 2023/10/4
 */
public class BeanFactory {
    /**
     * 已经加载到容器中的bean
     */
    private final BeanRegister beanRegister;
    /**
     * 从properties文件中加载到的bean 还没放到容器中
     */
    private final Map<String, BeanDefinition> beanDefinitionMap;

    public BeanFactory() {
        this.beanRegister = new BeanRegister();
        this.beanDefinitionMap = ResourceLoader.loadResource();
    }

    public Object getBean(String beanName) {
        Object bean = beanRegister.getBean(beanName);
        return Objects.nonNull(bean) ? bean : createBean(beanName);
    }

    private Object createBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        Optional.ofNullable(beanDefinition)
                .map(BeanDefinition::getBeanClass)
                .map(beanClass -> {
                    Object bean = null;
                    try {
                        bean = beanClass.newInstance();
                    } catch (InstantiationException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    return bean;
                }).ifPresent(obj -> beanRegister.registerBean(beanName,obj));
        return beanRegister.getBean(beanName);
    }
}
